﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 数据模型接口
/// </summary>
public interface IModelData
{
    /// <summary>
    /// 初始化 Model
    /// </summary>
    void Init();

}

/// <summary>
/// 数据模型管理器,可以管理需要全局使用的数据模型
/// </summary>
public class ModelDataManager : MonoBehaviour
{
    public static Dictionary<string, IModelData> uiModels = new Dictionary<string, IModelData>();

    public static void AddModel<T>(string key = null, T model = default(T)) where T : IModelData, new()
    {
        if (key == null) key = typeof(T).FullName;
        if (!uiModels.ContainsKey(key))
        {
            if (model == null) model = new T();
            uiModels.Add(key, model);
        }
        else
        {
            Debug.LogWarning("Model 已存在:" + key);
        }
    }

    public static void DeleteModel<T>(string key) where T : IModelData
    {
        if (key == null) key = typeof(T).FullName;
        if (uiModels.ContainsKey(key))
        {
            uiModels.Remove(key);
        }
    }

    public static void DeleteAllModel<T>() where T : IModelData
    {
        var temp = new List<string>();
        foreach (var item in uiModels)
        {
            if (typeof(T).IsInstanceOfType(item.Value))
            {
                Debug.Log("移除 Model:" + item.Key);
                temp.Add(item.Key);
            }
        }
        for (int i = 0; i < temp.Count; i++)
        {
            uiModels.Remove(temp[i]);
        }
    }

    public static void DeleteAllModel()
    {
        uiModels.Clear();
    }

    public static void DeleteModel(string key)
    {
        if (uiModels.ContainsKey(key))
        {
            uiModels.Remove(key);
        }
    }

    public static T GetModel<T>(string key = null) where T : IModelData, new()
    {
        if (key == null) key = typeof(T).FullName;
        if (uiModels.ContainsKey(key))
        {
            return (T)uiModels[key];
        }
        else
        {
            T model = new T();
            AddModel(key, model);
            Debug.Log("自动加入 Model" + key);
            return model;
        }
    }

}
